function initMenu() {
    $.getJSON('/json/menu.json', function(data) {
        var html = "";
        $.each(data, function(entryIndex, entry) {
            if (entry['menu']) {
                html += "<div class='menuHead'>" + entry['menu'] + "</div>";
            }
            
            if (entry['data']) {
            	var linkInThisMenu = false;
            	$.each(entry['data'], function(entryIndex, entry) {
                    if (window.location.pathname == entry['link'])
                    	linkInThisMenu = true;
                });
            	if(linkInThisMenu)
                	html += "<div class='collapsable'>";
            	else
            	    html += "<div class='" + entry['class'] + "'>";
                $.each(entry['data'], function(entryIndex, entry) {
                    if (window.location.pathname == entry['link'])
                        html += "<div class='currentMenuItem'>" + entry['item'] + "</div>";
                    else
                        html += "<a style='width:100%' href='" + entry['link'] + "'><div class='menuItem'>" + entry['item'] + "</div></a>";
                });
                html += "</div>";
            }
        });
        $('.menu').prepend(html);
        activeMenu();
    });
}

function activeMenu() {

    $('div.menuHead').click(function() {
        var checkElement = $(this).next();

        if ((checkElement.is('div.collapsable')) && (!checkElement.is(':visible'))) {
            checkElement.slideDown('fast');
            return false;
        }
        if ((checkElement.is('div.collapsable')) && (checkElement.is(':visible'))) {
            checkElement.slideUp('fast');
            return false;
        }
    });
    
	$('div.menuHead').mouseenter(function() {
	    $this=$(this);
	    $this.css('background-color', '#136');
	    $this.next().css('background-color', '#456');
	}).mouseleave(function() {
        $this=$(this);
        $this.css('background-color', '');
        $this.next().css('background-color', '');
	});
    
	$('div.menuItem').mouseenter(function() {
		$(this).css('background-color', '#456');
	}).mouseleave(function() {
		$(this).css('background-color', '');
	});
}

$(document).ready(function() {
    initMenu();
});
